<template>
	<view>
		<!-- 顶部自定义导航 -->
		<tn-nav-bar fixed>
			<view slot="default" class="nav-title" @click="expertInfo" v-if="liveInfo.authorName">
				<!-- <image class="picture" :src="liveInfo.avatar"></image>
				{{liveInfo.authorName||''}} -->
			</view>
			<tn-notice-bar :list="list" mode="horizontal" :speed="140" :playStatus="paused"></tn-notice-bar>
		</tn-nav-bar>
		<!-- 页面内容 -->
		<view :style="{paddingTop: vuex_custom_bar_height + 'px'}">
			<view class="video" v-if="liveStatus == '0'">
				<live-player :src="liveInfo.flvpullurl" mode="live" autoplay @statechange="onStateChange" :enable-auto-rotation='true'
					@error="onError" style="width: 100%; height: 440rpx;"></live-player>
			</view>
			<view class="video" v-if="liveStatus == '1'">
				<view class="live-wait">
					<view class="wait-tip">直播未开始</view>
					<view class="appointment" @click="appointmentFunc">{{liveInfo.userLiveStatus=='0'?'预约直播':'已预约'}}
					</view>
					<view class="countdown">距离开播还有：{{time}}</view>
				</view>
			</view>
			<view class="video" v-if="liveStatus == '2'">
				<video id="myVideo" :src="liveInfo.flvurl" @error="videoErrorCallback" controls @click="togglePlay"
					@play="onPlay" @pause="onPause" :poster='liveInfo.coverImage' style="width: 100%; "></video>
			</view>
			<tn-tabs :list="tabList" :isScroll="false" :current="current" name="tabName" @change="changeTab"></tn-tabs>

			<block v-if="current == '0'">
				<!-- 直播专家： -->
				<view class="nav-title">
					<view class="title-list" v-for="(item,index) in liveInfo.expertVOList"  @click="expertInfo(item.id)">
						<image class="picture" :src="item.avatar"></image>
						{{item.name||''}}
					</view>
				</view>
				<view class="title" v-if="liveStatus == '0'" style="color: #9b9b9b;font-weight: 200;display: flex;">
					在线人数：{{liveInfo.viewperson}}
					<view @click="collect"
						:class="liveInfo.collectStatus=='0'?'cllect-btn':'cllect-btn cllect-btn-active'">
						{{liveInfo.collectStatus=='0'?'收 藏':'取消收藏'}}
					</view>
				</view>
				<view class="title" v-else style="color: #9b9b9b;font-weight: 200;display: flex;">
					浏览人数：{{liveInfo.viewperson}}
					<view @click="collect"
						:class="liveInfo.collectStatus=='0'?'cllect-btn':'cllect-btn cllect-btn-active'">
						{{liveInfo.collectStatus=='0'?'收 藏':'取消收藏'}}
					</view>
				</view>

				<view class="title">{{liveInfo.livetitle}}</view>
				<!-- 页面 WXML -->
				<view class="rich-text-container">
					<rich-text class="text" :nodes="liveInfo.livedes"></rich-text>
				</view>

				<view class="tag">{{liveInfo.createtime}}</view>
			</block>
			<block v-if="current == '1'">
				<view class="comment-title">{{commentList.length>0?'评论':'暂无评论'}}</view>
				<view class="comment-box">
					<view class="comment-list" v-for="(item,index) in commentList" :key="index">
						<image class="user-img" src="../../static/user.png"></image>
						<view class="info">
							<view class="user-name">
								<view>{{item.userName}}</view>
								<view>{{item.createTime}}</view>
							</view>
							<view class="comment-text">
								{{item.commentValue}}
							</view>
						</view>
					</view>
				</view>
				<view class="footer" v-if="commentStatus">
					<view class="comment" @tap="showComment">
						<text class="tn-icon-write" style="font-size: 35rpx;"></text>
						<input class="comment-input" disabled placeholder="说点什么..." />
					</view>
					<!-- <view class="thumbs-up" @click="like">
			<text class="tn-icon-like" v-if="dataInfo.likeStatus=='0'"></text>
			<text style="color: #e83a30;" class="tn-icon-like-fill" v-else></text>
			<span style="font-size: 28rpx;">{{dataInfo.likeCount}}</span>
		</view> -->
					<!-- <view class="collect" @click="collect">
						<text class="tn-icon-star" v-if="liveInfo.collectStatus=='0'"></text>
						<text style="color: #e83a30;" class="tn-icon-star-fill" v-else></text>
						<span style="font-size: 28rpx;">{{liveInfo.collectCount}}</span>
					</view> -->
					<view class="share">
						<button open-type="share" class="share-btn"><text class="tn-icon-share-circle"
								style="font-size: 40rpx;"></text>分享</button>
					</view>
				</view>
			</block>
		</view>
		<ygc-comment ref="ygcComment" :placeholder="'发布评论'" @pubComment="pubComment"></ygc-comment>
	</view>
</template>

<script>
	import {
		getLiveComment,
		getCommentByContent,
		saveLiveComment,
		getLiveInfo,
		contentLikes,
		contentFolder,
		reservationLive,
		getCommentSwitchStatus
	} from '@/util/index.js'
	export default {
		data() {
			return {
				list: [],
				liveInfo: {},
				commentList: [],
				liveStatus: '0', //0是已经开播，1是未开播，2是已结束
				id: '',
				tabList: [{
					tabName: '直播介绍'
				}, {
					tabName: '问题互动'
				}],
				current: 0,
				time: '',
				commentStatus: false,
				videoContext: null,
				isPlaying: false,
				countdown:null
			};
		},
		onLoad(option) {
			this.liveStatus = option.liveStatus
			this.id = option.id
			this.getComment()
			this.getData()
			this.getSwitchStatus()
		},
		onReady() {
			// 创建视频上下文
			this.videoContext = uni.createVideoContext('myVideo', this)
		},
		// 发送给朋友/群聊
		onShareAppMessage(res) {
			// 来自页面内分享按钮
			if (res.from === 'button') {
				console.log(res.target)
			}
			return {
				title: this.liveInfo.livetitle, // 分享标题
				path: `/articleVideo/live-video/live-video?id=${this.id}`, // 分享路径，可带参数
				imageUrl: this.liveInfo.livepic // 分享图片（可选）
			}
		},

		// 分享到朋友圈（仅微信小程序支持）
		onShareTimeline() {
			return {
				title: this.liveInfo.livetitle,
				query: '', // 页面参数 key=value
				imageUrl: this.liveInfo.livepic // 分享图片
			}
		},
		onUnload() {
			clearInterval(this.countdown);
		},
		methods: {
			processRichText(htmlContent) {
				console.log(htmlContent)
				// 处理图片样式
				let processedHtml = htmlContent.replace(/<img([^>]*)>/gi, (match, attributes) => {
					// 添加内联样式
					return `<img style="width:100% !important;height:auto !important;display:block;max-width:100% !important;" ${attributes}>`;
				});
				return processedHtml
			},
			changeTab(e) {
				this.current = e
			},
			appointmentFunc() {
				if (this.liveInfo.userLiveStatus == '1') return
				reservationLive({
					liveId: this.liveInfo.id
				}).then((res) => {
					this.liveInfo.userLiveStatus = '1'
					uni.showToast({
						title: '预约成功！',
						icon: 'none'
					})
				})
			},
			like() {
				contentLikes({
					contentId: this.id
				}).then((res) => {
					uni.showToast({
						title: this.liveInfo.likeStatus == '1' ? '点赞已取消！' : '感谢点赞！',
						icon: 'none'
					})
					this.liveInfo.likeStatus = this.liveInfo.likeStatus == '1' ? '0' : '1'
				})
			},
			collect() {
				contentFolder({
					contentId: this.id,
					type: 1
				}).then((res) => {
					uni.showToast({
						title: this.liveInfo.collectStatus == '1' ? '收藏已取消！' : '感谢收藏！',
						icon: 'none'
					})
					this.liveInfo.collectStatus = this.liveInfo.collectStatus == '1' ? '0' : '1'
				})
			},
			videoErrorCallback: function(e) {
				uni.showModal({
					content: e.target.errMsg,
					showCancel: false
				})
			},
			showComment() {
				this.$refs.ygcComment.toggleMask('show')
			},
			pubComment(e) {
				saveLiveComment({
					groupid: this.id,
					msgcontent: e
				}).then((res) => {
					uni.showToast({
						title: '评论已发送！',
						icon: 'none'
					})
					this.getComment()
				})
			},
			getComment() {
				getLiveComment({
					liveId: this.id,
					page: 1,
					limit: 500
				}).then((res) => {
					this.commentList = res.list

				})
			},
			onStateChange(e) {
				console.log('直播状态变化:', e.detail.code);
			},
			onError(e) {
				console.error('直播播放错误:', e.detail.errMsg);
			},
			getData() {
				getLiveInfo({
					id: this.id
				}).then((res) => {
					if(res.livedes){
						res.livedes =this.processRichText(res.livedes)
					}
					this.liveInfo = res
					if (this.liveStatus == '1') {
						this.calculateCountdown()
					}
				})
			},
			expertInfo(id) {
				uni.navigateTo({
					// url: `/templatePage/expert-info/expert-info?id=${this.liveInfo.expertId}`
					url: `/templatePage/expert-info/expert-info?id=${id}`
				})
			},
			// 倒计时计算方法
			calculateCountdown() {
				this.countdown = setInterval(()=>{
					const targetDate = new Date(this.liveInfo.starttime)
					// 获取当前时间
					const now = new Date().getTime();
					// 计算时间差（毫秒）
					const distance = targetDate - now;
					// 如果时间已过或正好到达
					if (distance <= 0) {
						this.liveStatus = '0'
						clearInterval(this.countdown);
						return
					}
					// 计算天、时、分、秒
					const days = Math.floor(distance / (1000 * 60 * 60 * 24));
					const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
					const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
					const seconds = Math.floor((distance % (1000 * 60)) / 1000);
					this.time = `${days}天${hours}时${minutes}分${seconds}秒`
				}, 1000)
				// setTimeout(() => {
				// 	this.calculateCountdown()
				// }, 1000)
			},
			getSwitchStatus() {
				getCommentSwitchStatus().then((res) => {
					this.commentStatus = res.status == "1" ? true : false
				})
			},
			togglePlay() {
				// 获取 video 组件的引用
				if (this.isPlaying) {
					this.videoContext.pause()
				} else {
					this.videoContext.play()
				}
			},
			onPlay() {
				this.isPlaying = true
			},
			onPause() {
				this.isPlaying = false
			},
		}
	}
</script>

<style lang="less">
	* {
		box-sizing: border-box;
	}

	.video {
		width: 100%;
		min-height: 300rpx;

		video {
			width: 100%;
		}
	}

	.ti-conten {
		padding-bottom: 200rpx;
	}

	.nav-title {
		// display: flex;
		// align-items: center;
		// background-color: #6aa1fa;
		// width: 250rpx;
		// height: 55rpx;
		// justify-content: center;
		// border-radius: 30rpx;
		// color: #FFFFFF;
		// margin: 15rpx auto 0;
		display: flex;
		padding: 0 20rpx;
		align-items: center;
		// background-color: #6aa1fa;
		width: 100%;
		height: 55rpx;
		// justify-content: space-between;
		// border-radius: 30rpx;
		// color: #FFFFFF;
		margin: 10rpx 0;
		.title-list{
			display: flex;
			padding: 10rpx 20rpx;
			align-items: center;
			background-color: rgba(185, 185, 185, 0.1);
			// color: #FFFFFF;
			border-radius: 10rpx;
			margin-right: 20rpx;
			border-left:3rpx solid #cbcbcb ;
		}
	}

	.title {
		padding: 20rpx;
		font-size: 30rpx;
		font-weight: 600;
	}

	.cllect-btn {
		background-color: #007AFF;
		color: #FFFFFF;
		margin-left: 20rpx;
		width: 140rpx;
		height: 45rpx;
		text-align: center;
		line-height: 45rpx;
		border-radius: 10rpx;
		font-size: 28rpx;
	}

	.cllect-btn-active {
		background-color: #9b9b9b;

	}

	.text {
		padding: 0 20rpx 50rpx 20rpx;
		display: block;
		font-size: 30rpx;
	}

	.tag {
		font-size: 24rpx;
		color: #9b9b9b9b;
		padding: 10rpx 20rpx;
	}

	.comment-box {
		width: 100%;
		padding: 0 20rpx;

		.comment-list {
			display: flex;
			align-items: center;
			margin-bottom: 20rpx;
			padding: 0 20rpx;

			.user-img {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				margin-right: 20rpx;
			}

			.info {
				flex: 1;

				.user-name {
					color: #9b9b9b9b;
					font-size: 26rpx;
					margin-bottom: 10rpx;
					display: flex;
					justify-content: space-between;
					width: 100%;
					align-items: center;
				}

				.comment-text {
					font-size: 28rpx;
				}
			}
		}
	}

	.comment-title {
		padding: 10rpx 20rpx;
		color: #9b9b9b;
	}

	.picture {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		margin-right: 20rpx;
	}

	.footer {
		position: fixed;
		bottom: 0;
		width: 100%;
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx 60rpx 20rpx;
		border-top: 1rpx solid #eeeeee;
		font-size: 45rpx;
		background-color: #FFFFFF;

		.comment {
			display: flex;
			border: 1rpx solid #eeeeee;
			align-items: center;
			padding: 5rpx 15rpx;
			border-radius: 20rpx;
			font-size: 28rpx;
			flex: 1;
			height: 70rpx;
		}

		.thumbs-up {
			width: 90rpx;
			text-align: right;
		}

		.collect {
			width: 90rpx;
			margin-top: 10rpx;
			text-align: center;
		}

		.share {
			width: 100rpx;
			text-align: center;
			margin-top: 8rpx;

			.share-btn {
				width: 100rpx;
				font-size: 25rpx;
				padding: 0;
				display: flex;
				align-items: center;
				background: none;
			}
		}
	}

	.live-wait {
		width: 100%;
		min-height: 300rpx;
		background-color: #000000;
		opacity: 0.6;

		.wait-tip {
			font-weight: 500;
			font-size: 40rpx;
			color: #FFFFFF;
			text-align: center;
			padding-top: 80rpx;
		}

		.appointment {
			width: 192rpx;
			height: 56rpx;
			border-radius: 200rpx 200rpx 200rpx 200rpx;
			border: 2rpx solid #00C8C8;
			font-size: 28rpx;
			color: #00C8C8;
			text-align: center;
			line-height: 56rpx;
			margin: 30rpx auto 0;
		}

		.countdown {
			font-size: 30rpx;
			font-weight: bold;
			color: #D0D5D7;
			text-align: center;
			margin-top: 30rpx;
		}
	}

	/* 页面 WXSS */
	.rich-text-container {
		width: 100%;
	}

	/* 设置 rich-text 内部图片宽度为 100% */
	.rich-text-container img {
		width: 100% !important;
		height: auto !important;
		display: block;
		max-width: 100% !important;
	}
</style>
